package com.chaopei.myexception;

import java.io.*;

/**
 * @Author Corday 天涯
 * @Date 2022/3/9 10:47
 */
public class MyException {
    public static void main(String[] args) {
        // managerException();
//        ioException(new File("c:/ChaoPei"));
//        readDisk();
        System.out.println(play());
    }

    //  1.捕捉异常并管理它
    public static void managerException() {
        int a = 10, b = 10;
        try {
            int rs = a / b;
        } catch (ArithmeticException ex) {
            ex.printStackTrace();
            System.out.println(ex.getMessage());
            System.out.println("算术运算异常");
        } finally {//用于关闭对象，比如：流，数据库连接

        }
    }

    //    2.输入/输出流异常
    public static void ioException(File file) {
        if (file.isFile()) {
            System.out.println("文件名：" + file.getName());
        } else {
            System.out.println("文夹名：" + file.getName());
            File[] fs = file.listFiles();
            for (File f : fs) {
                //递归找文件
                ioException(f);
            }
        }
    }

    // 3.读磁盘文件
    public static void readDisk() {
        //1.创建输入流对象，打开文件
        InputStream in = null;
        try {
            in = new FileInputStream("c:/ChaoPei/poem.txt");
            //2.读取数据
            byte[] buffer = new byte[in.available()];
            String str = "";
            while (in.read(buffer) != -1) {//读完后返回-1
                str += new String(buffer, 0, buffer.length, "gb2312");
            }
            //3.关闭流
            in.close();
            System.out.println(str);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 4.自定义异常的管理
    public static String play() throws MyArithmException {
        int x = 525, y = 100;
        if (x > 999) {
           throw  new MyArithmException("数字过大,x<=999");
        } else if (y == 0) {
           throw new MyArithmException("除数为0异常");
        }
        return "x/y=" + (x / y);
    }
}
